{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# User's Guide, Chapter 21: Ordering and Sorting of Stream Elements"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Inside a stream, each object has a position and thus an order in the :class:`~music21.stream.Stream`.  Up until now we've seen two different ways to describe the position of an element (such as a :class:`~music21.note.Note`) in a stream.  The first is the index of the object in the stream (a number in square brackets) and the second is the `offset`.\n",
    "\n",
    "Let's take a simple Stream:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from music21 import *\n",
    "s = stream.Measure()\n",
    "ts1 = meter.TimeSignature('3/4')\n",
    "s.insert(0, ts1)\n",
    "s.insert(0, key.KeySignature(2))\n",
    "s.insert(0, clef.TrebleClef())\n",
    "s.insert(0, note.Note('C#4'))\n",
    "s.insert(1, note.Note('D#4'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have inserted three elements that take up no space (a TimeSignature, KeySignature, and a Clef) and two elements that take up 1.0 quarter notes (the default length of a Note object). You might notice that the signatures and clef were inserted in a strange order. Don't worry, we'll get to that in a bit.  \n",
    "\n",
    "In addition to inserting elements at particular places in a Stream, we can append an element to the end of the Stream:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAc4AAABqCAYAAAA1HLH8AAAACXBIWXMAAB7CAAAewgFu0HU+AAAWXUlEQVR4nO3deZgcdZ3H8Xcmk4QJgSQcIRCOBBISWAgYBMJGEaOAiAqsB6cgC48c4gKKLrAouwoBVy5ZVBARBQHhQSLoEtYschiIkOUWcgFJIEBIyJ3Jncz+8a2iq2uquuvurpnP63n66Zrq6qrfdM/0t+tX39/3B8UZDywC2oG9CzyuiIhI6ZwGbAA6nNurQFtDWyQiItKkTgA2UQma7m1CA9rSE7gBOKcBxxYREanrQGAdnYNmh7N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4xraIFKQJF21y2Js+36dx8c799MTtEPyl2Zoww7Y39fGTFvUvbRg1YXAKgzd7HlsOHZN0qWhDSIFSXLG+W7E7TYCj9R4vDd2YRzgvxO0Q/KVdmhDC11/Wri8HIiN5ZwP3BOyjf9/V0MbRAqS5IzzyYjb/RiYV+PxU6nU6dTQhcbYj/Baqec7jyfVARxM9VjdDcATKfbZHdyNFfaP63IswSTqdcqnsULxcxMcS0QSmEPtmpc3UPtstp9nHwqajTORdAklcW+Livm1SqMPNhH8JGpPaB50C8pqPgTLwKz1vOeA4+j6892K5CbpOM4JwC+c5bVYMYQtsVkW7seqn9RyLTaQdxOaxqiR2rHELL++pJ9VfjWdK+AsT7nPruZc4LqYz5mHjaMOGqLgDm04EstY3xn7IrsQm6loMvBm0saKSDo9qZ6w+g9Ev176r57nXZJL6yQtDW0oRpTZUdzbcuBwdKYoUmq7Ylmz7j/2Y9QeqtIP+Kln+wfRh0CzWk3yoLkB+FjxTS6lWoFzI9aFexHRxnGKSEmMxrqO3H/2dqzb9otYGv1+wNFYhuACz3a/p/M4NGkei0geNL/UgPaWVVDgnIH1yrhfQuPUqhWRktgBmzswygdrO9Y9q0LSze1u4gfNZcAXGtHYErsUe+3eBj5wltMUeReRkhkL/BIb5+n/UJ0O/ADr3pXmp1kbirENlsTTQjazo4hIifUH9gSGkT47UxpDQxuKpcApUhJJh6PUsxwNPSi7qcBI4DBsrtTB2Af4YmxIw1+x4UciIt1KXoFTuoZNWNk9TRUmIuJIUqtWRESk21LgFGluS7FhPvVmGhKRgqirVqS5LcYyltsb3A4RcShwijSHTb57r6hT+YlIAVSIQKQ5LMMqNt1J5+L4ItJE/h98SjROx063gAAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 53,
       "width": 231
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "e = note.Note('E4')\n",
    "s.append(e)\n",
    "s.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we're pretty sure that the C# will be the fourth element in the Stream, which is referred to as `[3]` and the D# will be the fifth, or `[4]`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<music21.note.Note C#>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<music21.note.Note D#>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[4]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The E will be `[5]` but we can also get it by saying it's the last element, or `[-1]`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<music21.note.Note E>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The other way to describe the position of an element is by its offset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "e.offset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may recall from previous discussions that the `offset` of an element is its position within the last referenced Stream it was attached to.  Thus, if you want to know the offset of an element within a particular Stream, it is always safer to use one the following methods: `.getOffsetBySite(stream)`: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "e.getOffsetBySite(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or to call `stream.elementOffset(element)`. This is a little bit faster so it's what we use internally. It will always give the same result if `e` is in `s`, but if `e` might not be in `s` but be derived from an element in `s` then `.getOffsetBySite` will trace the `.derivation.chain()` to find it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.elementOffset(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to find all the elements at a particular offset, call `.getElementsByOffset` on the Stream.  Note that if any elements are found it returns a `StreamIterator`, so you will need to use the square bracket index to reference it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<music21.note.Note E>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.getElementsByOffset(2.0)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This description might seem a bit obnoxious, but it is necessary because you can get multiple elements back, such as with an offset range:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(<music21.note.Note D#>, <music21.note.Note E>)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y = s.getElementsByOffset(1.0, 3.0)\n",
    "(y[0], y[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "At this point, you might think that you know everything about how elements are positioned in a Stream, but there are a few more points that are important and point to the power of `music21`.  Let's show the Stream as a text file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 3/4>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{2.0} <music21.note.Note E>\n"
     ]
    }
   ],
   "source": [
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Something has happened: the `TrebleClef` object which was inserted third has now become the first element of the Stream. The `KeySignature` and `TimeSignature` objects have also switched position.  Now all three are in the order we'd expect to see them in a score:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(<music21.clef.TrebleClef>,\n",
       " <music21.key.KeySignature of 2 sharps>,\n",
       " <music21.meter.TimeSignature 3/4>)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(s[0], s[1], s[2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Even though they have the same `.offset`, each of these objects knows its place in the Stream, because of something called `.classSortOrder`.  Each Class and each instance of the class has a default sort order so that if it is at the same offset as a member of a different class, one will sort before the other:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 2, 4)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(s[0].classSortOrder, s[1].classSortOrder, s[2].classSortOrder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In fact, `classSortOrder` is present not just on objects but on classes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 2, 4)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(clef.Clef.classSortOrder, key.KeySignature.classSortOrder, meter.TimeSignature.classSortOrder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notes have a higher `classSortOrder` and thus sort even later, hence why the C# appears after the clefs and signatures:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(20, 20)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(note.Note.classSortOrder, base.Music21Object.classSortOrder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are a few elements that sort even lower than Clefs because they usually refer to the area of the composition that precedes the clef:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-5, -25, -30)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(bar.Barline.classSortOrder, instrument.Instrument.classSortOrder, metadata.Metadata.classSortOrder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The numbers are actually completely arbitrary (it could be -6.432 instead of -5), only the order of numbers (-25 is less than -5) matters.\n",
    "\n",
    "If we put a second TimeSignature into the stream at offset 0 (like some pieces do with multiple interpretations for meter), it will have a tie for its .offset and .classSortOrder.  Which one will come first? It's the first one inserted:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 3/4>\n",
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{2.0} <music21.note.Note E>\n"
     ]
    }
   ],
   "source": [
    "ts2 = meter.TimeSignature('6/8')\n",
    "s.insert(0, ts2)\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we wanted to make sure that the two TimeSignatures appeared in a particular order regardless of when they were inserted, there is one way to do so: set the `.priority` attribute on the TimeSignature.  Every Music21Object has a `priority` attribute, and the default is `0`. Negative numbers make an element sort before a default element. Positive numbers sort after.  \n",
    "\n",
    "Let us insert two more notes into the stream, at offsets 1 and 2, but we'll make the note at offset 1 come before the D# and the one at offset 2 come after the E, so we have a chromatic scale fragment:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 3/4>\n",
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{2.0} <music21.note.Note E>\n",
      "{2.0} <music21.note.Note E#>\n"
     ]
    }
   ],
   "source": [
    "d = note.Note('D')\n",
    "d.priority = -10\n",
    "eis = note.Note('E#')\n",
    "eis.priority = 10\n",
    "s.insert(1.0, d)\n",
    "s.insert(2.0, eis)\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some things to note about priority:\n",
    "\n",
    "(1) Priority changes immediately affect the sorting of the Stream (in v.3 or above).  Before that if you wanted to change the priority of an object, you'd need to remove it and then reinsert it. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 3/4>\n",
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{1.0} <music21.note.Note D>\n",
      "{2.0} <music21.note.Note E>\n",
      "{2.0} <music21.note.Note E#>\n"
     ]
    }
   ],
   "source": [
    "d.priority = 20\n",
    "s.remove(d)\n",
    "s.insert(1.0, d)\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(2) Priority is currently a global property that affects all Streams that an object is in. This is behavior that may change in later versions.\n",
    "\n",
    "(3) Priority overrides `classSortOrder`.  So if we wanted to move the 6/8 TimeSignature `(ts2)` to sort before the 3/4 `(ts1)`, it is not enough to shift the priority of `ts2` and reinsert it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 3/4>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{1.0} <music21.note.Note D>\n",
      "{2.0} <music21.note.Note E>\n",
      "{2.0} <music21.note.Note E#>\n"
     ]
    }
   ],
   "source": [
    "ts2.priority = -5\n",
    "s.remove(ts2)\n",
    "s.insert(0.0, ts2)\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the 6/8 TimeSignature appears before the clef and key signature.  A fix for this would involve assigning some priority to each object connected to its sort order:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{0.0} <music21.meter.TimeSignature 3/4>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{1.0} <music21.note.Note D>\n",
      "{2.0} <music21.note.Note E>\n",
      "{2.0} <music21.note.Note E#>\n"
     ]
    }
   ],
   "source": [
    "for el in s.getElementsByOffset(0.0):\n",
    "    el.priority = el.classSortOrder\n",
    "\n",
    "ts2.priority = 3  # between KeySignature (priority = 2) and TimeSignature (priority = 4)\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is enough about sorting for most of purposes, so feel free to move on to :ref:`Chapter 22: Graphing Music21 Streams <usersGuide_22_graphing>`, but for anyone who wants to go into more depth, there's a \"behind the scenes\" tour below.\n",
    "\n",
    "\n",
    "## Advanced Sorting and the `sortTuple`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How does sorting actually work? `Music21` uses six attributes to determine which elements go before or after each other.  The six-element tuple that determines sort order can be accessed on any `Music21Object` by calling the method `.sortTuple()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SortTuple(atEnd=0, offset=0.0, priority=4, classSortOrder=4, isNotGrace=1, insertIndex=0)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#_DOCS_SHOW ts1.sortTuple()\n",
    "ts1.sortTuple().modify(insertIndex=0) #_DOCS_HIDE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SortTuple(atEnd=0, offset=0.0, priority=3, classSortOrder=4, isNotGrace=1, insertIndex=118)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#_DOCS_SHOW ts2.sortTuple()\n",
    "ts2.sortTuple().modify(insertIndex=118) #_DOCS_HIDE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A :class:`~music21.sorting.SortTuple` is a lightweight class derived from the `NamedTuple` object that can be compared using the `>` and `<` operators. Each of the elements is compared from left to right; if there is a tie on one attribute then the next one becomes important:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ts1.sortTuple() > ts2.sortTuple()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`SortTuples` live in their own module :ref:`moduleSorting` and have a few cool features.  Since the main point of comparison is offset, SortTuples can compare against plain integers or floats or Fractions by comparing their offsets (and `atEnd`, which we'll get to in a second)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "st = sorting.SortTuple(atEnd=0, offset=10.0, priority=1, classSortOrder=4, isNotGrace=1, insertIndex=5)\n",
    "st > 8.0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because they can be unwieldly to display, `SortTuple`s have a `.shortRepr()` call which summarizes the main information in them: the offset, the priority, the classSortOrder, and the insertIndex."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'10.0 <1.4.5>'"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "st.shortRepr()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, the third element, priority, decides the order. The first attribute, atEnd, is 0 for normal elements, and 1 for an element stored at the end of a Stream. Let's add a courtesy KeySignature change at the end of `s`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SortTuple(atEnd=1, offset=0.0, priority=0, classSortOrder=2, isNotGrace=1, insertIndex=120)"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ks2 = key.KeySignature(-3)\n",
    "s.storeAtEnd(ks2)\n",
    "#_DOCS_SHOW ks2.sortTuple()\n",
    "ks2.sortTuple().modify(insertIndex=120) #_DOCS_HIDE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Putting a rightBarline on a Measure has the same effect:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SortTuple(atEnd=1, offset=0.0, priority=0, classSortOrder=-5, isNotGrace=1, insertIndex=121)"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rb = bar.Barline('double')\n",
    "s.rightBarline = rb\n",
    "#_DOCS_SHOW rb.sortTuple()\n",
    "rb.sortTuple().modify(insertIndex=121) #_DOCS_HIDE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'End <0.-5.121>'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#_DOCS_SHOW rb.sortTuple().shortRepr()\n",
    "rb.sortTuple().modify(insertIndex=121).shortRepr() #_DOCS_HIDE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The next three attributes (offset, priority, classSortOrder) have been described.  `isNotGrace` is 0 if the note is a grace note, 1 (default) if it is any other note or not a note.  Grace notes sort before other notes at the same offset and priority.  The last attribute is an ever increasing index of the number of elements that have had SiteReferences added to it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(Advanced topic: the order that elements were inserted is used in order to make sure that elements do not shift around willy-nilly, but it's not something to use often or to rely on for complex calculations. For this reason, we have not exposed it as something easy to get, but if you need to access it, here's the formula:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "tags": [
     "nbval-ignore-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 104)"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(ts1.sites.siteDict[id(s)].globalSiteIndex, ts2.sites.siteDict[id(s)].globalSiteIndex)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Streams have an attribute to cache whether they have been sorted, so that `.sort()` only needs to be called when a change has been made that alters the sort order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.isSorted"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Calling a command that needs a particular order (`.show()`, `.getElementsByClass()`, `[x]`, etc.) automatically sorts the Stream:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[0]\n",
    "s.isSorted"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There is one more way that elements in a Stream can be returned, for advanced\n",
    "uses only.  Each Stream has an `autoSort` property.  By default it is On.  But\n",
    "if you turn it off, then elements are returned in the order they are added\n",
    "regardless of offset, priority, or classSortOrder.  Here is an example of that:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{20.0} <music21.meter.TimeSignature 3/4>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{1.0} <music21.note.Note D>\n",
      "{2.0} <music21.note.Note E>\n",
      "{2.0} <music21.note.Note E#>\n",
      "{20.0} <music21.bar.Barline type=double>\n",
      "{20.0} <music21.key.KeySignature of 3 flats>\n"
     ]
    }
   ],
   "source": [
    "s.autoSort = False\n",
    "ts1.setOffsetBySite(s, 20.0)\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The setting `autoSort = False` can speed up some operations if you already know that all the notes are in order. Inside the stream/core.py module you’ll see some even faster operations such as `_insertCore()` and `_appendCore()` which are even faster and which we use when translating from one format to another. After running an `_insertCore()` operation, the Stream is in an unusuable state until `core.elementsChanged()` is run, which lets the Stream ruminate over its new state as if a normal `insert()` or `append()` operation has been done. Mixing `_insertCore()` and `_appendCore()` commands without running `_elementsChanged()` is likely to have disasterous consequences. Use one or the other."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to get back to the sorted state, just turn `autoSort = True`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{1.0} <music21.note.Note D>\n",
      "{2.0} <music21.note.Note E>\n",
      "{2.0} <music21.note.Note E#>\n",
      "{20.0} <music21.meter.TimeSignature 3/4>\n",
      "{20.0} <music21.bar.Barline type=double>\n",
      "{20.0} <music21.key.KeySignature of 3 flats>\n"
     ]
    }
   ],
   "source": [
    "s.autoSort = True\n",
    "s.isSorted = False\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that this is a destructive operation. Turning `autoSort` back to `False` won’t get you back the earlier order:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0.0} <music21.clef.TrebleClef>\n",
      "{0.0} <music21.key.KeySignature of 2 sharps>\n",
      "{0.0} <music21.meter.TimeSignature 6/8>\n",
      "{0.0} <music21.note.Note C#>\n",
      "{1.0} <music21.note.Note D#>\n",
      "{1.0} <music21.note.Note D>\n",
      "{2.0} <music21.note.Note E>\n",
      "{2.0} <music21.note.Note E#>\n",
      "{20.0} <music21.meter.TimeSignature 3/4>\n",
      "{20.0} <music21.bar.Barline type=double>\n",
      "{20.0} <music21.key.KeySignature of 3 flats>\n"
     ]
    }
   ],
   "source": [
    "s.autoSort = False\n",
    "s.show('text')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "sphinx_links": {
     "any": true
    }
   },
   "source": [
    "Now that you've gotten everything sorted out, let's move on to :ref:`Chapter 22: Graphing Music21 Streams <usersGuide_22_graphing>`"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
